/**
 * Created by TomSean on 2017/10/30.
 */
var AssignmentMessage = function ($parent) {
    this.sysUtils = new kendoUtils();
    this.$parent = $parent;
    this.init();
    return this;
}
AssignmentMessage.prototype = {
    init : function () {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent.find('.screenContent'));
        var functionArray = [
            {fName:'show_param', fs:this.showParam},
            {fName:'manual_send', fs:this.openSendWindow},
            {fName:'find_data', fs:this.findMessageList},
            {fName:'cancel_data', fs:this.cancelMsg}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#messageStatus'), parentModelKey:BASIS.ASSIGNMENT_STATUS.ROOT}, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#messageOperation'), parentModelKey:BASIS.OPERATION_BEHAVIOR.ROOT}, this);
        this.initColumn();
        this.findMessageList();
    },
    cancelMsg : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        notification({title : '提示', message : '是否确认取消发送？'}, 'confirm', {
            callback : function () {
                var ids = '';
                $this.$parent.find('[name="assign_message_id"]:checked').each(function(inx, itm) {
                    ids += $(itm).val() + ',';
                });
                if (ids=='') {
                    notification({title:'提示', message:'请至少选择一条数据'},'info');
                    return;
                }
                JsonpAjax(baseApiPath + 'assign/task/cancel?id='+ids, '', 'json', function () {
                    $this.findMessageList();
                }, true);
            }
        })
    },
    openSendWindow : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        $this.sendWindow = $this.sysUtils.openWindow($this.sendWindow, {
            title : '手动下发数据',
            height : "685px",
            width : "800px",
            resizable : false,
            content : "views/parkLotCenter/assignment/issueTask.html",
        }, true);

    },
    showParam : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        $this.$parent.find('.screenContent').toggle();
    },
    getDetail : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var id = $this.selectRowId;
        JsonpAjax(baseApiPath + 'assign/task/detail/' + id, '', 'json', function (res) {
            $this.cache = res;
            $this.openDetail();
            $this.selectRowId = undefined;
        });
    },
    openDetail : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        $this.detailDiv = $this.sysUtils.openWindow($this.detailDiv, {
            title : '查看详情',
            height : "400px",
            width : "850px",
            resizable : false,
            content : "views/parkLotCenter/assignment/content.html"
        }, true);
    },
    initColumn : function () {
        var $this = this;
        var columns = [
            {
                width : 30,
                headerTemplate : '<input type="checkbox" gridId="assignMessageList" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="assign_message_id" value="${id}" />',
            },
            {
                width : 190,
                title : '设备编号',
                field : 'controlCode'
            },
            {
                width : 50,
                title : '操作用户',
                field : 'createUserName'
            },
            {
                width : 50,
                title : '操作方式',
                template : '#:Utils.getModelNameByParentKey(BASIS.OPERATION_BEHAVIOR.ROOT, messageOperation)#'
            },
            {
                width : 50,
                title : '消息状态',
                template : '#:Utils.getModelNameByParentKey(BASIS.ASSIGNMENT_STATUS.ROOT, messageStatus)#'
            },
            {
                width : 120,
                title : '近一次发送时间',
                field : 'lastSendTime'
            },
            {
                width : 120,
                title : '生成时间',
                field : 'createTime'
            },
            {
                width : 200,
                title : '所属任务批次',
                template : '#:data.task.id #'
            }
        ];
        $this.sysUtils.createGird($this.$parent.find('#assignMessageList'), {
            selectable : 'single',
            autoSync : true,
            columnMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function (e) {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find('input[type=checkbox]').val();
                });
                $this.selectRowId = selected[0];
            },
            dataBound : function() {
                var $list = $this.$parent.find("#assignMessageList");
                $list.find("tr").unbind("dblclick");
                $list.find("tr").dblclick(function(e){
                    var grid = $list.data("kendoGrid");
                    var dataItem = grid.dataItem(grid.select());
                    //打开查看窗口
                    $this.selectRowId = dataItem['id'];
                    $this.getDetail();
                });
            }
        });
    },
    findMessageList : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var grid = $this.$parent.find('#assignMessageList').data('kendoGrid');
        var params = $this.sysUtils.getBindDocJson($this.models.bindFieldArray);
        var dataT = {'jsonParam' : JSON.stringify(params)};
        var dataSource = $this.sysUtils.getDataSource({url : baseApiPath + 'assign/task/list', data : dataT, dataType : 'odata'});
        grid.setDataSource(dataSource);
    }
}

var AssignmentManual = function ($parent) {
    this.sysUtils = new kendoUtils();
    this.$parent = $parent;
    this.init();
    return this;
}
AssignmentManual.prototype = {
    init : function () {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName:'rush_data', fs:this.findControlMsg},
            {fName:'get_all', fs:this.getAll},
            {fName:'send_data', fs:this.sendData},
            {fName:'clear', fs:this.clearAllCard},
            {fName:'getCount', fs:this.getControlCount},
            {fName:'get_detail', fs:this.getDetail}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        var $this = this;
        this.findControlMsg();
    },

    clearAllCard : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        notification({title : '提示', message : '是否确认清除设备内所有数据？'}, 'confirm', {
            callback : function () {
                var codes = '';
                $this.$parent.find('.regular-checkbox:checked').not('#data_item_model .regular-checkbox').each(function (inx, itm) {
                    codes += $(itm).val() + ',';
                });
                var params = {'password':'', 'controlCode':codes};
                JsonpAjax(baseApiPath + 'assign/task/clear', JSON.stringify(params), 'json', function (res) {
                    $this.findControlMsg();
                });
            }
        });
    },
    getControlCount: function (e) {
        var code = $(e).parents('.case2').find('.regular-checkbox').val();
        JsonpAjax(baseApiPath + 'assign/task/control/count?controlCode='+code, '', 'json', function (res) {
            $(e).html(isEmpty(res.count) ? 0 : res.count);
        },true);
    },
    findControlMsg : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        JsonpAjax(baseApiPath + 'assign/task/controlMsg', '', 'json', function (res) {
            if (isEmpty(res)) {
                notification({title:'获取控制台数据', message:'没有找到相关的发送数据'},'info')
                return;
            }
            $this.$parent.find('#data_list').html('');
            var addMsgCount = res['addMsgCount'];
            var cancelMsgCount = res['cancelMsgCount'];
            var delMsgCount = res['delMsgCount'];
            var successMsgCount = res['successMsgCount'];
            var msgCount = res['msgCount'];
            var controlCode = res['controlCode'];
            var orgLevelName = res['orgLevelName'];
            var controlJson = res['controlJson'];
            var controlMsgCount = res['controlMsgCount'];
            $this.$parent.find('#addMsgCount').html(addMsgCount);
            $this.$parent.find('#cancelMsgCount').html(cancelMsgCount);
            $this.$parent.find('#delMsgCount').html(delMsgCount);
            $this.$parent.find('#successMsgCount').html(successMsgCount);
            $this.deployData(res.controlSendMsgViewList);
        });
    },
    getAll : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        if ($this.$parent.find('.regular-checkbox').not('input:checked').length > 0) {
            $this.$parent.find('.case2').each(function(inx, itm) {
                $(itm).find('.regular-checkbox').prop('checked', true);
            });
        } else {
            $this.$parent.find('.case2').each(function(inx, itm) {
                $(itm).find('.regular-checkbox').prop('checked', false);
            });
        }
    },
    sendData : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }

        var controlCodes = '';
        $this.$parent.find('.regular-checkbox:checked').not('#data_item_model .regular-checkbox').each(function(inx, itm) {
            if ($(itm).val() == '' || $(itm).val() == undefined) {
                return;
            }
            controlCodes += $(itm).val() + ',';
        });
        if (isEmpty(controlCodes)) {
            notification({title:'警告', message:'请至少选择一行数据执行下发'}, 'info');
            return;
        }
        JsonpAjax(baseApiPath + 'assign/task/sendMsg?controlCodes='+controlCodes, '', 'json', function (res) {
            notification({title:'成功', message:'已添加到下发队列'}, 'info');
            $this.findControlMsg();
        });
    },
    deployData : function (list) {
        if (isEmpty(list) || list.length == 0) {
            return;
        }
        for (var i = 0; i < list.length; i++) {
            var res = list[i];

            var addMsgCount = res['addMsgCount'];
            var updateMsgCount = res['updateMsgCount'];
            var delMsgCount = res['delMsgCount'];
            var successMsgCount = res['successMsgCount'];
            var msgCount = res['msgCount'];
            var controlCode = res['controlCode'];
            var orgLevelName = res['orgLevelName'];
            var controlJson = res['controlJson'];
            var controlMsgCount = res['controlMsgCount'];
            var controlDetail = res['controlJson'];
            var detail = controlDetail.basic.normal;
            var $model = this.$parent.find('#data_item_model').clone();
            $model.removeAttr('id');
            $model.find('.regular-checkbox').attr('id', 'checkbox-task-' + detail.deviceNumber);
            $model.find('.regular-checkbox').val(controlCode);
            $model.find('.checkbox-label').attr('for', 'checkbox-task-' + detail.deviceNumber);
            /**
             * autoRecognition : "0"
             * centerIp : "192.168.0.102"
             * centerPort : "5000"
             * clientIp : "192.168.0.100"
             * clientPort : "5000"
             * deviceNumber : "21"
             * deviceid : "5"
             * gatewayIp : "172.16.12.254"
             * greeting : "欢迎使用智能停车系统"
             * heartbeat : "2"
             * ip : "198.168.9.21"
             * ndsIp : "172.16.12.1"
             * port : "5000"
             * serverIp : "192.168.0.101"
             * serverPort : "5000"
             * subnetMask : "255.255.0.0"
             * synch : "600"
             */
            $model.find('.message_ip').html(detail.ip);
            $model.find('.gateway_ip').html(detail.deviceNumber);
            $model.find('.message_port').html(detail.port);
            $model.find('.message_dns').html(detail.ndsIp);
            $model.find('.item_new_data').html(addMsgCount);
            $model.find('.item_delete_data').html(delMsgCount);
            $model.find('.park_org_name').html(orgLevelName);

            this.$parent.find('#data_list').append($model);
            $model.show();
            this.deployData(list.controlSendMsgViewList);
        }
    }
}







